local DB = require("common.DB")
local ItemDefine = require("bag.ItemDefine")
local Lang = require("common.Lang")
local lua_mongo = _G.lua_mongo
local Log = require("common.Log")
local Msg = require("core.Msg")
local ShopHelp = require("shop.ShopHelp")
local Broadcast = require("broadcast.Broadcast")
local InnerDataManagerFW = require("innerdata.InnerDataManagerFW")
local InnerDataDefine = require("innerdata.Define")
local Grid = require("bag.Grid")
local MailLogicFW =require("mail.MailLogicFW")

--market = {market_uuid = {send_id = human._id, create_time = create_time, itemId = id, itemCnt = 1, yuanbao = yuanbao}}

local market_goods_max_time = 72 * 3600
local market_page_cnt = 5

function sendStatus(human, status)
  local sendMsg = Msg.gc.GC_MARKET_STATUS
  sendMsg.status = status
  Msg.send(sendMsg, human.fd)
end

--初始化
function db_init()
  if marketdb then
    return
  end
  marketdb = {}
  lua_mongo.find(DB.db_market)
  while true do
    local tb = {}
    if not lua_mongo.next(tb) then
      break
    end
    marketdb[tb._id] = tb
  end
end

local function db_insert(tb, time)
  if not(tb._id and tb.send_id and tb.yuanbao and tb.itemId and tb.itemCnt) then
    assert()
  end
  if marketdb[tb._id] then
    tb._id = _G.gen_oid()
  end 
  tb.create_time = time or os.time()
  lua_mongo.insert(DB.db_market, tb)
  marketdb[tb._id] = tb
  return marketdb[tb._id]
end
--移除
local query = {}
local function db_remove(tb)
--  if not(tb._id and tb.create_time and tb.send_id and tb.yuanbao and tb.itemId and tb.itemCnt and marketdb[tb._id]) then
--    assert()
--  end
  marketdb[tb._id] = nil
  query._id = tb._id
  lua_mongo.remove(DB.db_market, query)
end

local sort_by = {--排序类型，1,2是按物品颜色，3,4是按照总价，5,6是按照剩余时间,先降序后升序  
  [1] = function(a, b)
    return ItemDefine.getValue(a.itemId, "color") < ItemDefine.getValue(b.itemId, "color")
  end,
  [2] = function(a, b)
    return ItemDefine.getValue(a.itemId, "color") > ItemDefine.getValue(b.itemId, "color")
  end,
  [3] = function(a, b)
    return a.yuanbao < b.yuanbao
  end,
  [4] = function(a, b)
    return a.yuanbao > b.yuanbao
  end,  
  [5] = function(a, b)
    return a.create_time > b.create_time
  end,
  [6] = function(a, b)
    return a.create_time < b.create_time
  end,
}

--查询剩余时间
local function get_left_time(market)
  return math.max(0, market_goods_max_time - (os.time() - market.create_time))
end
local cache = {}
--构造寄售数据
local function make_market_data(human, out, market)
  out.market_uuid = market._id
  out.left_time = get_left_time(market)
  out.yuanbao = market.yuanbao
  Grid.create(cache, market.itemId, market.itemCnt)
  Grid.makeItem(cache, out.grid, 0, human)
  out.isMine = (market.send_id == human._id) and 1 or 0
end

--查询
function CG_MARKET_QUERY(human, m)
  if not sort_by[m.sort] then
    return Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_QUERY_ERR_SORT)
  end
  local tb = {}
  for k, v in pairs(marketdb) do
    local item_name = ItemDefine.getValue(v.itemId, "name")
    local marketId = ItemDefine.getValue(v.itemId, "marketId")
    if  (m.config_pos == marketId or m.config_pos == 0) and --human._id ~= v.send_id and
      (m.keyword == "" or string.find(item_name, m.keyword, 1, true)) and
      not v.recv_id and get_left_time(v) > 0 then
      tb[#tb + 1] = v
    end
  end
  table.sort(tb, sort_by[m.sort])
  local sendMsg = Msg.gc.GC_MARKET_QUERY
  local page = m.page
  local page_total = math.ceil(#tb / market_page_cnt)
  page = math.min(page, page_total)
  page = math.max(1, page)
  sendMsg.page = page
  sendMsg.page_total = page_total
  sendMsg.market_data[0] = 0
  if 0 < page_total then
    local aa = (page - 1) * market_page_cnt + 1
    local bb = math.min(aa + market_page_cnt - 1, #tb)
    for i = aa, bb do
      sendMsg.market_data[0] = sendMsg.market_data[0] + 1
      make_market_data(human, sendMsg.market_data[i - aa + 1], tb[i])
    end
  else
    sendMsg.page = 0
  end
  Msg.send(sendMsg, human.fd)
end

--打开我要寄售界面
function CG_MARKET_QUERY_ME(human)
--  if not sort_by[msg.sort] then
--    return Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_QUERY_ERR_SORT)
--  end
  local tb = {}
  for k, v in pairs(marketdb) do
    if v.send_id == human._id then
      tb[#tb + 1] = v
    end
  end
--  table.sort(tb, sort_by[msg.sort])
  local mm = Msg.gc.GC_MARKET_QUERY_ME
  mm.market_data[0] = 0
  for i=1,#tb do
    mm.market_data[0] = mm.market_data[0] + 1
    make_market_data(human, mm.market_data[i], tb[i])
  end
  Msg.send(mm, human.fd)
end
--购买，和下架
function CG_MARKET_PICK(human, m)
  local market = marketdb[m.market_uuid]
  if not market then
    return Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_ERR_ITEM_XIAJIA)
  end
  local tmp = {}
  if market.send_id == human._id then --下架,收回
    tmp.id = market.itemId
    tmp.cnt = market.itemCnt
    tmp.uuid = m.market_uuid
    tmp.yuanbao = market.yuanbao
    InnerDataManagerFW.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_MARKET_BACK, tmp)    
  else --购买
    if human._id == market.send_id then
      return
    end
    if human.db.yuanbao < market.yuanbao then
      return ShopHelp.onNoRMB(human)      
    end
    tmp._id = m.market_uuid
    tmp.send_id = market.send_id
    tmp.create_time = market.create_time
    tmp.itemId = market.itemId
    tmp.itemCnt = market.itemCnt
    tmp.yuanbao = market.yuanbao
    db_remove(market)
    InnerDataManagerFW.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_MARKET_BUY, tmp)
  end
end

function recycleSuccess(human, oType, info)
  local market = {}
  market._id = info.uuid
  db_remove(market)
  Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_ERR_ITEM_XIAJIA_SUCCESS)
  sendStatus(human, 3)
  CG_MARKET_QUERY_ME(human)
end
--寄售
function sell(human, oType, info)
  local len = 0
  for k, v in pairs(marketdb) do
    if v.send_id == human._id then
      len = len + 1
    end
  end
  if len >= 20 then
    return Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_ERR_SELL_LIST_FULL)
  end
  local market = {}
  market._id = info.uuid
  market.send_id = human._id
  market.itemId = info.id
  market.itemCnt = info.cnt
  market.yuanbao = info.yuanbao
  local insert = db_insert(market)
  if insert then    
    Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.MARKET_ERR_ITEM_SELL_SUCCESS)
    InnerDataManagerFW.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_MARKET_SELL, nil)
    sendStatus(human, 1)
  end  
  CG_MARKET_QUERY_ME(human)
  Log.write(Log.LOGID_OSS_MARKET, human._id, human.account, human.name, human.db.lv, insert.itemId, insert.itemCnt, insert.yuanbao, 1, insert._id, 0)
end

function buyFail(human, oType, info)
  if info.success then
    local shouxufei = 0
    if info.yuanbao < 10 then
      shouxufei = 1       
    else
      shouxufei = math.ceil(info.yuanbao * 0.1)
    end
    local nGridList = {}
    nGridList[1] = Grid.create(nil, ItemDefine.ITEM_ID_BIND_YUANBAO, info.yuanbao - shouxufei, 1)
    local str = string.format(Lang.MARKET_MAIL_SELL_SUCCESS, ItemDefine.getValue(info.itemId, "name"), info.itemCnt, 
      human.name, info.yuanbao, shouxufei, info.yuanbao - shouxufei)    
    MailLogicFW.addSystemMessage(info.send_id, Lang.MARKET_MAIL_SELL_TITLE, str, nGridList)
  else
    db_insert(info, info.create_time)
  end
end

InnerDataManagerFW.Register(InnerDataDefine.INNERDATA_TYPE_MARKET_BUY, buyFail)
InnerDataManagerFW.Register(InnerDataDefine.INNERDATA_TYPE_MARKET_BACK, recycleSuccess)
InnerDataManagerFW.Register(InnerDataDefine.INNERDATA_TYPE_MARKET_SELL, sell)

